// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { h, fragment } from '@knno/dom/jsx';
import { Grid, UIGrid } from '@knno/ui/jsx/grid';
import { Button } from '../../../dist/jsx/button';
import { bar } from './index.css';

function range(begin: number, end: number, step = 1) {
	return {
		[Symbol.iterator]: function* generateRange() {
			let x = begin - step;
			while (x < end - step) yield (x += step);
		},
	};
}

function genText() {
	return [...range(1, Math.random() * 30 + 1)]
		.map(() => {
			const v = 0x4e00 + Math.floor(Math.random() * (0x9fa5 - 0x4e00));
			return String.fromCharCode(v);
		})
		.reduce((p, v) => p + v);
}

export function ShowInfiniteGrid() {
	let tb: UIGrid;

	function addColumns() {
		tb.columns([
			{ title: '列1', key: 0, align: 'center', sortable: true, width: '200px', resizable: true },
			{ title: '列2', key: 1, sortable: true, width: '10%', resizable: true },
			{ title: '列3', key: 2, align: 'right', width: '10%', resizable: true },
			{ title: '列4', key: 3, width: '10%' },
			{ title: '列5', key: 4, width: '10%' },
			{ title: '列6', key: 4, width: '15%', resizable: true },
			{ title: '列7', key: 4, width: '15%', resizable: true },
		]);
	}

	let lines = 0;
	function addData(more: boolean) {
		const result: any[] = [];
		for (let i = 0; i < 50; i++) {
			lines++;
			const row = [];
			row.push(lines);
			row.push(genText());
			for (let j = 1; j < 4; j++) {
				row.push('text content ' + j);
			}
			result.push(row);
		}
		result.push({ section: '加载更多...' });
		console.log('data generated!');
		if (more) {
			setTimeout(() => {
				if (tb.rows().length > 0) {
					tb.rows().length -= 1;
				}
				tb.appendRows(result);
			}, 1000);
		} else {
			tb.rows(result);
		}
	}

	return (
		<>
			<h2>无限加载</h2>
			<div class={bar}>
				<Button
					type="danger"
					text="删除数据"
					onclick={() => {
						lines = 0;
						tb.rows([]);
					}}
				/>
			</div>
			<Grid
				section={{ key: 'section' }}
				ref={(t) => {
					tb = t;
					addColumns();
					addData(false);
				}}
				onscrollbottom={() => {
					const st = tb.scrollTop();
					console.log('scrollTop:', st);
					addData(true);
				}}
			/>
		</>
	);
}
